package cn.huhst.cas.weisiqian.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.Picture;
import cn.huhst.cas.weisiqian.service.PhotoWallService;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/AddPicture.do")
public class AddPicture extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(AddPicture.class);
	private String competitionName = null;
	private String pictureDesc = null;
	private String pictureName = null;
	private PhotoWallService photowallservice = null;
	private JSON json = new JSON();

	public AddPicture() {
		super();
		photowallservice = new PhotoWallService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		upload(request, response);
		save(response);
	}

	private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 判断是否是上传表单是否为multipart/form-data类型
		if (ServletFileUpload.isMultipartContent(request)) {
			logger.info("上传图片:");
			// 创建 DiskFileItemFactory工厂 对象
			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			// 创建DiskFileItemFactory的解析器对象
			ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
			// 设置上传头的编码格式
			fileUpload.setHeaderEncoding("UTF-8");
			// 设置文件上传大小的限制 为1M
			fileUpload.setFileSizeMax(1024 * 1024);
			// 注册监听 已经上传的进度
			fileUpload.setProgressListener(new ProgressListener() {
				@Override
				public void update(long pBytesRead, long pContentLength, int pItems) {
					logger.debug("到现在为止,  " + pBytesRead + " 字节已上传，总大小为 " + pContentLength);
				}
			});

			try {
				// 解析request请求
				List<FileItem> fileItems = fileUpload.parseRequest(request);
				// fileItem 对应<input type="file" name="upload" id="upfile" />
				// fileItem <input type="text" name="user" />
				// 遍历操作
				for (FileItem fileItem : fileItems) {
					// 首先判断 是否是 普通的文本
					if (fileItem.isFormField()) {
						// 获取字段name值
						String name = fileItem.getFieldName();
						// 字段name值 相对应的value
						String value = fileItem.getString();
						logger.info("普通文本：name=" + name + "  value=" + value);
						if ("competitionName".equals(name)) {
							competitionName = name;
						} else if ("pictureDesc".equals(name)) {
							pictureDesc = name;
						}
					} else {
						// 获取上传文件的名称 文件名称可能是(c:\xxxx\xxx\xx.jpg(IE浏览器) 或者
						// xx.jpg(火狐浏览器));
						String fileName = fileItem.getName();
						// 如果在IE浏览器中 ---> 先解析出xx.jpg
						int index = fileName.lastIndexOf("\\");
						// 进行判断是否 含有\
						if (index != -1) {
							// 含有\ 就解析出xx.jpg
							fileName = fileName.substring(index + 1);
						}
						logger.info("照片名称=" + fileName);
						// 添加时间戳 保证上传的文件名称唯一
						fileName = System.currentTimeMillis() + "_" + fileName;
						logger.info("添加时间戳后的文件名=" + fileName);
						pictureName = fileName;
						// 设置保存的路径
						String path = request.getServletContext().getRealPath("/img/upload");
						// 创建保存的文件
						File file = new File(path, fileName);
						logger.info("照片保存目录=" + file.getAbsolutePath());
						// 获取请求的输入流对象
						InputStream is = fileItem.getInputStream();
						// 输出流对象
						FileOutputStream fos = new FileOutputStream(file);
						// 缓冲区大小
						byte[] buffer = new byte[1024];
						// 读取的长度
						int len = 0;
						// 读取 如果读取的结果为-1 证明读取完毕,否则继续读取
						while ((len = is.read(buffer)) != -1) {
							// 写入文件
							fos.write(buffer, 0, len);
						}
						// 关闭流的操作
						fos.close();
						is.close();
						// 删除临时文件
						fileItem.delete();

					}
				}
				// 转发到 显示所有上传照片的servlet处理
				request.getRequestDispatcher("ListPicture.do").forward(request, response);

			} catch (FileUploadException e) {
				// 获取错误的异常信息
				String message = e.getMessage();
				// The field upload exceeds its maximum permitted size of
				// 1048576 bytes.
				// 如果存在 限制文件大小的字符 就提示 文件上传过大
				if (message.contains("permitted size of")) {
					json.putErrorMSG("文件上传过大");
				}
			}

		}
	}

	private void save(HttpServletResponse response) throws IOException {
		if (json.isEmpty()) {
			Picture picture = new Picture(competitionName, pictureDesc, pictureName);
			json = picture.checkFormat();
			if (json.isEmpty()) {
				boolean result = photowallservice.addPicture(picture);
				if (result) {
					json.putOKMSG("保存照片" + picture.getPicturename() + "成功");
					logger.error("保存照片" + picture.getPicturename() + "成功");
				} else {
					json.putErrorMSG("保存照片" + picture.getPicturename() + "失败");
					logger.error("保存照片" + picture.getPicturename() + "失败");
				}
			} else {
				json.putErrorMSG("格式不符合要求");
				logger.error("json=" + json);
			}
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
